package com.example.beangenerate.util;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Service
public class GenerateFile {
    public void generateFile(String modelPath,Map param,String resultFileName){
        //获取文件地址
        String path = ClassLoader.getSystemResource(modelPath).getPath();
        //根据文件地址找到文件
        File file = new File(path);
        //获取文件绝对路径
        Path absolutePath = Paths.get(file.getAbsolutePath());
        for(int i = 0;i<4;i++){
            file = file.getParentFile();
        }
        String resultPath = file+"".concat("\\src\\main\\resources\\templates\\generate\\");

        //2.将读入的文件转为string 字符串
        //读取其内容
        String data = null;
        BufferedWriter out = null;
        try {
            data = new String(Files.readAllBytes(absolutePath), "UTF8");

            //创建模版引起上下文 并传入要替换的参数
            VelocityContext vc = new VelocityContext(param);
            //创建StringWriter对象 其内部是对StringBuffer进行的操作
            StringWriter writer = new StringWriter();
            //模版引起开始替换模版内容
            Velocity.evaluate(vc, writer, "code_gen", data);
            //替换之后的字符串
            String sqlmapResult = writer.getBuffer().toString();

            //4.将新的字符串输出到文件

            //新文件的路径+文件名+后缀
            //路径
            if(!new File(resultPath).exists()){
                new File(resultPath).mkdirs();
            }
            resultPath = resultPath.concat(resultFileName);
            File sqlmapOutFile = new File( resultPath);
            if (!sqlmapOutFile.exists()) {
                sqlmapOutFile.createNewFile();
            }
            Path outPath = Paths.get(sqlmapOutFile.getAbsolutePath());
            //将文件写入
            out = Files.newBufferedWriter(outPath);
            out.write(sqlmapResult);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
